<?php

namespace app\service;

use app\model\admin\SysMember;
use app\model\admin\SysMemberMenu;
use app\model\admin\SysMemberUserMenu;
use think\facade\Db;

class MemberService
{
    public static function getInfo($user_id)
    {
        $user = SysMember::where('id', $user_id)->find();
        if ($user == null) {
            return error('用户不存在');
        }

        $is_child = false;
        if ($user->parent_id > 0) {
            $is_child = true;
        }

        $user_role = ['member'];

        if ($is_child === false) {
            $permissions = SysMemberMenu::where('menu_type', 'F')->column('perms');
            // $permissions = ['*:*:*'];
        } else {
            $user_role_menu_id = SysMemberUserMenu::whereIn('user_id', $user->id)->column('menu_id');
            $permissions = SysMemberMenu::where('menu_type', 'F')->whereIn('id', $user_role_menu_id)->column('perms');
        }

        return success([
            'permissions' => $permissions,
            'roles' => $user_role,
            'user' => $user,
            'user_type' => 'user',
        ]);
    }

    public static function getRouters($user_id)
    {
        $user = SysMember::where('id', $user_id)->find();
        $is_child = false;
        if ($user->parent_id > 0) {
            $is_child = true;
        }

        if ($is_child == false) {
            $menus = SysMemberMenu::whereIn('menu_type', ['M', 'C'])->order('order_num', 'asc')->select();
        } else {
            //获取会员菜单
            $user_menus_id = SysMemberUserMenu::whereIn('user_id', $user->id)->column('menu_id');
            if ($user_menus_id) {
                $user_menus_id = array_unique($user_menus_id);
            }
            //获取菜单
            $menus = SysMemberMenu::whereIn('id', $user_menus_id)->whereIn('menu_type', ['M', 'C'])->order('order_num', 'asc')->select();
        }

        $menus_tree = makeTree($menus->toArray(), 'id', 'parent_id');

        $menus_routes = generateRouters($menus_tree);
        return $menus_routes;
    }
}
